home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: SORTing problem c++
- Date: Sun, 28 Jan 96 02:09:32 GMT
- Organization: none
- Message-ID: <822794972snz@genesis.demon.co.uk>
- References: <310AE6D3.6119@pi.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <310AE6D3.6119@pi.net> heggie@pi.net "heggie" writes:
-
- >I'm used to normal c
- >just recent i switched to c++, now i am stucked
- >with a program that did work in c but doesn't
- >in c++.
- >it is a program that sorts the 'argv' array,
- >what can I DO???
- >
- >
- >
- >#include <stdio.h>
- >#include <stdlib.h>
- >#include <string.h>
- >
- >
- >int sort_function(char **a, char **b)
- >{
- > return( strcmp(*a, *b));
- >}
- >
- >
- >int main(int argc, char **argv)
- >{
- > int
- > x;
- >
- > qsort(argv, argc, sizeof(char*), sort_function);
- >
- > for (x = 0; x < argc; x++)
- > printf("%s\n", argv[x]);
- > return 0;
- >}
-
- Your program isn't valid C, let alone C++ (the fact that it happened
- to work on your particular system is not relevant to this). The most
- obvious problem is that qsort() requires a comparison function of the form
-
- int sort_function(const void *, const void *);
-
- which yours clearly isn't. An ANSI C compiler should have complained about
- this, as will a C++ compiler. Instead use something like:
-
- static int sort_function(const void *a, const void *b)
- {
- return strcmp(*(const char *const *)a, *(const char *const *)b);
- }
-
- Your other problem is that it is not legal in C to modify the argv array
- of pointers, so you need to make a copy of it and sort that.
-
-
- int main(int argc, char **argv)
- {
- int x;
-
- if (argc > 0) {
- char **const argp = malloc(argc * sizeof(*argp));
-
- if (argp == NULL)
- exit(EXIT_FAILURE);
-
- memcpy(argp, argv, argc * sizeof(*argp));
-
- qsort(argp, argc, sizeof *argp, sort_function);
-
- for (x = 0; x < argc; x++)
- printf("%s\n", argp[x]);
-
- free(argp);
- }
-
- return 0;
- }
-
- Note that, like your code, this includes argv[0] in the sort which is the
- program name.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-